package handlers

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"user/api/request"
	"user/dao"
	"user/pkg"
)

func Register(c *gin.Context) {
	var data request.RegisterRequest
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"Code": 500,
			"Msg":  "失败",
			"Data": nil,
		})
		return
	}
	user, _ := dao.GetUser(data.Name)
	if user != nil {
		c.JSON(http.StatusOK, gin.H{
			"Code": 500,
			"Msg":  "该账号已被注册了",
			"Data": nil,
		})
		return
	}
	result := dao.Register(data.Name, pkg.Md5([]byte(data.Password)))
	c.JSON(http.StatusOK, gin.H{
		"Code": 200,
		"msg":  "Success",
		"Data": result,
	})
}

func Login(c *gin.Context) {
	var data request.LoginRequest
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"Code": 500,
			"Msg":  "失败",
			"Data": nil,
		})
		return
	}
	result := dao.Login(data.Name, pkg.Md5([]byte(data.Password)))
	token, _ := pkg.GetJwtToken(result.Id)
	c.JSON(http.StatusOK, gin.H{
		"Code": 200,
		"Msg":  "Success",
		"Data": token,
	})
}
